package com.cmccgz.udacs_landlord_webapp.main.user.userinfo;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.cmccgz.baselibrary.base.BaseFragment;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.bean.UserInfo;
import com.cmccgz.udacs_landlord_webapp.main.host.CHostActivity;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;
import com.orhanobut.logger.Logger;

import java.io.File;

/**
 * @author INX
 * 编辑用户信息fragment
 */
public class UserInfoChangedFragment extends BaseFragment implements View.OnClickListener, UserInfoContract.ChangeInfoView {
    private UserInfoActivity parentActivity;
    private TextView tv_header;
    private EditText et_old;
    private TextView tv_sex;
    private EditText et_nickName;
    private UserInfoContract.ChangeInfoPresenter presenter;
    private Dialog selectSexDialog;
    private UserInfo userInfo;
    private ViewHelper viewHelper;

    public static UserInfoChangedFragment instance() {
        return new UserInfoChangedFragment();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_useinfo_change;
    }

    @Override
    protected void initView() {
        parentActivity = ((UserInfoActivity) mContext);
        initDatas();
        viewHelper = ViewHelper.instance(this);
        if (viewHelper != null) {
            viewHelper.setTitle(R.string.title_userinfo_change);
            viewHelper.setBackTextVisable(true);
            viewHelper.setTextRightVisable(true);
            viewHelper.setRightText(R.string.right_text_userinfochange);
        }
        tv_header = ((TextView) findViewById(R.id.tv_header));
        tv_sex = ((TextView) findViewById(R.id.tv_sex));
        et_nickName = ((EditText) findViewById(R.id.et_nickName));
        et_old = ((EditText) findViewById(R.id.et_old));

        refreshViewByUserInfo();

        new UserInfoChangedPresenter(this);
        tv_sex.setOnClickListener(this);
        tv_header.setOnClickListener(this);
    }


    private void initDatas() {
        UserInfo userInfoEdit = parentActivity.getUserInfoEdit();
        UserInfo userInfo = parentActivity.getUserInfo();
        if (isSaveInstance) {
            this.userInfo=userInfoEdit!=null?userInfoEdit:userInfo!=null?userInfo:null;
        }else{
            this.userInfo=userInfo!=null?userInfo:null;
        }
        if (this.userInfo!=null) {
            this.userInfo=this.userInfo.copyNewInstance();
            parentActivity.setUserInfoEdit(this.userInfo);
        }else{
            showToast("未获取到用户信息！");
            parentActivity.setUserInfoEdit(null);
            parentActivity.backEditUserInfo();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                back();
                break;
            case R.id.tv_right:
                showLoadingDialog("正在保存用户信息...");
                refreshUserInfo();
                presenter.changeUserInfo(userInfo);
                break;
            case R.id.tv_header:
                refreshUserInfo();
                String head_id = userInfo.getHead_id();
                String headerUrl = (!StringUtils.isEmpty(head_id))&&new File(head_id).exists() ? head_id : userInfo.getImagePath();
                parentActivity.showUserHeader(headerUrl);
                break;
            case R.id.tv_sex:
                hideSoftKeyboard(tv_sex);
                selectSex();
                break;
            case R.id.btn_men:
                tv_sex.setText(R.string.sex_man);
                dismissSelectDialog();
                break;
            case R.id.btn_women:
                tv_sex.setText(R.string.sex_women);
                dismissSelectDialog();
                break;
            case R.id.btn_cancel:
                dismissSelectDialog();
                break;

        }
    }

    public void back() {
        boolean noChanged = isNoChanged();
        if (noChanged) {
            parentActivity.backEditUserInfo();
        }else{
            if (alertDialog==null) {
                showConfirmDialog("提示", "用户信息已修改，是否保存？", "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        viewHelper.getTv_right().performClick();
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        parentActivity.backEditUserInfo();
                    }
                });
            }else{
                alertDialog.show();
            }
        }
    }

    public boolean isNoChanged() {
        refreshUserInfo();
        boolean noChanged = UserInfo.isSameUserInfo(parentActivity.getUserInfo(), userInfo);
        Logger.v(getClass().getSimpleName()+"-back-noChanged："+noChanged);
        return noChanged;
    }

    /**
     * 刷新当前view里面的用户信息
     */
    private void refreshUserInfo() {
//        userInfo.setHead_id("http://n6.cmsfile.pg0.cn/group2/M00/2D/39/Cgqg2VaxrgWAAou0AADBw1QHSlQ633.jpg");
        userInfo.setSex(tv_sex.getText().toString());
        userInfo.setAge(et_old.getText().toString());
        userInfo.setNick_name(et_nickName.getText().toString());
    }

    /**
     * 刷新当前布局为最新的userinfo
     */
    private void refreshViewByUserInfo() {
        if (userInfo!=null) {
            tv_sex.setText(userInfo.getSex() == null ? "" : userInfo.getSex());
            et_nickName.setText(userInfo.getNick_name() == null ? "" : userInfo.getNick_name());
            et_old.setText(userInfo.getAge() == null ? "" : userInfo.getAge());
        }
    }
    /**
     * 隐藏选择性别dialog
     */
    private void dismissSelectDialog() {
        if (selectSexDialog != null) {
            selectSexDialog.dismiss();
        }
    }

    /**
     *保存用户信息成功
     */
    @Override
    public void changeInfoSuccess() {
        dismissLoadingDialog();
        showToast(R.string.tips_userinfo_save_success);
        parentActivity.backEditUserInfo();
        mContext.sendBroadcast(new Intent(CHostActivity.UPDATE_USERINFO));
        parentActivity.updateUserInfo();
    }

    /**
     * 修改用户信息失败
     * @param msg
     */
    @Override
    public void changeInfoError(String msg) {
        dismissLoadingDialog();
        showToast(msg);
    }

    @Override
    public void setPresenter(UserInfoContract.ChangeInfoPresenter presenter) {
        this.presenter = presenter;
    }

    /**
     * 选择性别
     */
    private void selectSex() {
        if (selectSexDialog == null) {
            View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_sex_select, null);
            selectSexDialog=new Dialog(mContext,R.style.DialogForAppcompat);
            selectSexDialog.setContentView(contentView);
            contentView.findViewById(R.id.btn_men).setOnClickListener(this);
            contentView.findViewById(R.id.btn_women).setOnClickListener(this);
            contentView.findViewById(R.id.btn_cancel).setOnClickListener(this);
        }
        if (!selectSexDialog.isShowing()) {
            selectSexDialog.show();
            Window window = selectSexDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.height=WindowManager.LayoutParams.WRAP_CONTENT;
            attributes.width=WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(attributes);
        }
    }

    /**
     * 更新头像信息
     */
    public void updateHeaderUrl(UserInfo userInfo){
        if ( this.userInfo==null) {
            this.userInfo=userInfo;
        }else{
            this.userInfo.setHead_id(userInfo.getHead_id());
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putSerializable("userInfo",userInfo);
        if (userInfo!=null) {
            parentActivity.setUserInfoEdit(userInfo);
        }
        super.onSaveInstanceState(outState);
    }
}
